#include "iostream"
#include "stdlib.h"
 
#include "cv.h"
#include "highgui.h"
 
using namespace std;
int main(){
    cvNamedWindow("My Window", CV_WINDOW_AUTOSIZE);
    int say;
     bool first = true;
    CvCapture *input;
    input =  cvCaptureFromCAM(0);
     CvSize imgSize;
 imgSize.width = 640;
 imgSize.height = 480;
    IplImage* greyImage = cvCreateImage( imgSize, IPL_DEPTH_8U, 1);
 IplImage* colourImage;//cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
 IplImage* movingAverage = cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
 IplImage* difference=cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
 IplImage* temp=cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
 difference = cvCreateImage( imgSize, IPL_DEPTH_8U, 3);
 for(;;){

  //Get a frame from the input video.
  colourImage = cvQueryFrame(input);
 
  //If there are no more frames, jump out of the for.
  if( !colourImage )
  {
   break;
  }
  
  //If this is the first time, initialize the images.
  if(first)
  {
   difference = cvCloneImage(colourImage);
   temp = cvCloneImage(colourImage);
   cvConvertScale(colourImage, movingAverage, 1.0, 0.0);
   first = false;
  }
  //else, make a running average of the motion.
  else
  {
   cvRunningAvg(colourImage, movingAverage, 0.020, NULL);
  }
 
  //Convert the scale of the moving average.
  cvConvertScale(movingAverage,temp, 1.0, 0.0);
 
  //Minus the current frame from the moving average.
  cvAbsDiff(colourImage,temp,difference);
  
  //Convert the image to grayscale.
  cvCvtColor(difference,greyImage,CV_RGB2GRAY);
  
  //Convert the image to black and white.
  cvThreshold(greyImage, greyImage, 70, 255, CV_THRESH_BINARY);
  
  //Dilate and erode to get people blobs
  cvDilate(greyImage, greyImage, 0, 10);
  cvErode(greyImage, greyImage, 0, 10);
   cvShowImage("My Window", difference);
   say=cvCountNonZero(greyImage);

/*   if(268800<=say && say<=307200){
   cout<<"Hassas 1: "<<say<<"\n";
   }else if(230400<=say && say<268800){
    cout<<"Hassas 2: "<<say<<"\n";         
   }else if(192000<=say && say<230400){
    cout<<"Hassas 3: "<<say<<"\n";    
   }else if(153600<=say && say<192000){
    cout<<"Hassas 4: "<<say<<"\n";         
   }else if(115200<=say && say<153600){
    cout<<"Hassas 5: "<<say<<"\n";         
   }else if(76800<=say && say<115200){
    cout<<"Hassas 6: "<<say<<"\n";         
   }else if(38400<=say && say<76800){
    cout<<"Hassas 7: "<<say<<"\n";         
   }else if(say<38400){
    cout<<"Hassas 8: "<<say<<"\n";         
   }*/
     if(38400<=say){
        cout<<"Hareket var\n "<<say<<"\n";
       // is_motion = true;
  }
  
  //Wait for the user to see it.
  cvWaitKey(5);
  
}
 cvReleaseImage(&temp);
 cvReleaseImage(&difference);
 cvReleaseImage(&greyImage);
 cvReleaseImage(&colourImage);
 cvDestroyWindow("My Window");
 
 cvReleaseCapture(&input);
    
    }
